package com.dongqb.common;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javax.swing.DefaultListModel;
import com.dongqb.bean.StockInfo;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;

public class WebUtil {
	private static final String suggestUrl = "https://suggest3.sinajs.cn/suggest/type=&key={}&name=suggestdata_{}";

	/**
	 * 获取建议股票
	 * @param input
	 * @return
	 */
	public static List<String> getSuggestLst(String input) {
		List<String> lst = new ArrayList<>();
		String rad = RandomUtil.randomNumbers(6);
		String url = StrUtil.format(suggestUrl, input, rad);
		String res = HttpUtil.get(url);
		// 解析结果
		String parseStr = res.substring(res.indexOf("suggestdata") + 20, res.lastIndexOf("\";"));
		if (parseStr.length() < 10) {
			return null;
		}
		String[] arrStr = parseStr.split(";");

		for (int i = 0; i < arrStr.length; i++) {
			String[] tp = arrStr[i].split(",");
			if (!tp[1].equals("11")) {
				// 除了a股以外的暂时不加入，还要处理其他市场的数据结构 太麻烦
				continue;
			}
			lst.add(tp[0] + " " + tp[3]);
		}
		return lst;
	}

	private static final String stockInfoUrl = "http://qt.gtimg.cn/q=";

	/**
	 * 获取股票实时数据
	 * 
	 * @param inputLst
	 * @return
	 */
	public static void updateStockInfos(DefaultListModel<StockInfo> listModel) {
		if(listModel==null || listModel.getSize()==0) {
			return;
		}
		LinkedHashMap<String, StockInfo> mapRes = new LinkedHashMap<>();
		StringBuffer bhs=new StringBuffer();
		int size=listModel.getSize();
		for (int i = 0; i < size; i++) {
			String bh=listModel.get(i).getBh();
			bhs.append(bh).append(",");
			mapRes.put(bh, listModel.get(i));
		}
		

		String url = stockInfoUrl + bhs;
		String res = HttpUtil.get(url);
		// 解析结果
		String[] arrStr = res.split("=\"");
		for (int i = 0; i < arrStr.length; i++) {
			String[] d = arrStr[i].split("~");
			if (d.length < 3) {
				continue;
			}
			String type = "sh";
			if (!"1".equals(d[0])) {
				type = "sz";
			}
			String name = d[1];
			String bh = type + d[2];
			double kpj = Double.parseDouble(d[5]);
			double spj = Double.parseDouble(d[3]);
			double zd = NumberUtil.parseDouble(d[32]);
			StockInfo item = mapRes.get(bh);
			if (item == null) {
				item = new StockInfo();
			}
			item.setBh(bh);
			item.setMc(name);
			item.setXj(d[3]);
			item.setUpdateTime(d[30]);
			if (kpj == 0 || spj == 0) {
				item.setXj("停牌");
				item.setZd("+0%");
			} else {
				if (zd >= 0) {
					item.setZd("+" + zd + "%");
				} else {
					item.setZd(zd + "%");
				}
			}
			item.setData(d);
		}
	}
}
